package book.crypto;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

/**
 * 解密文件中的加密数据
 */
public class CipherInputStreamTest {

	public static void main(String[] args) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
		
		KeyGenerator gen = KeyGenerator.getInstance("des");
		SecretKey key = gen.generateKey();
		Cipher cipher = Cipher.getInstance("DES");
		
		cipher.init(Cipher.ENCRYPT_MODE, key);
		CipherOutputStream out = new CipherOutputStream(new FileOutputStream("secret.txt"), cipher);
		DataOutputStream dos = new DataOutputStream(out);
		dos.writeUTF("涂有");
		dos.flush();
		dos.close();
		
		cipher.init(Cipher.DECRYPT_MODE, key);
		CipherInputStream in = new CipherInputStream(new FileInputStream("secret.txt"), cipher);
		DataInputStream dis = new DataInputStream(in);
		String output = dis.readUTF();
		System.out.println(output);
		dis.close();
	}
}
